import React, { useState, useCallback,useMemo,useContext,useEffect  } from 'react'
import { useNavigate } from 'react-router-dom'
import { NavBar, Image, List, Button, Steps, Ellipsis, Stepper, Checkbox,SwipeAction } from 'antd-mobile'
import { baseUrl } from '@/utils/request'

import context from '@/store/context'
import {useLogin} from '@/hooks'
import {withLogin} from '@/hoc'

function Cart() {
    const {cartlist,userInfo,dispatch} = useContext(context)
    const navigate = useNavigate();
    const gotoDetail = useCallback((id) => {
        navigate('/goods/' + id)
    }, [])
    const back = () => {
        navigate(-1)
    }
    const totalPrice = useMemo(() => cartlist.reduce((prev, item) => prev + item.sales_price * item.qty, 0), [cartlist])
    
    // // 判断用户是否登录
    // const isLogin = useMemo(() => !!userInfo.authorization, [userInfo])
    // console.log('isLogin',isLogin)
    // useEffect(()=>{
    //     if(!isLogin){
    //         navigate('/login')
    //     }

    // },[isLogin])

    // useLogin();
    
    return <div>
        <NavBar onBack={back} right={<Button color='primary' fill='none'>编辑</Button>}>购物车</NavBar>
        <Steps current={0}>
            <Steps.Step title='购物车' />
            <Steps.Step title='确认订单' />
            <Steps.Step title='支付' />
        </Steps>
        <List>
            {
                cartlist.map(item => (
                    <SwipeAction
                        key={item._id}
                        rightActions={[
                            {
                              key: 'delete',
                              text: '删除',
                              color: 'danger',
                              onClick:()=>{
                               dispatch({type:'remove',payload:{_id:item._id}})
                              }
                            },
                          ]}
                    >
                    <List.Item prefix={<Image width={60} src={baseUrl + item.img_url} onClick={gotoDetail.bind(null, item._id)} />}>
                        <Ellipsis content={item.goods_name} rows={2} />
                        <p className='price'><span>{item.sales_price}</span></p>
                        <Stepper
                            value={item.qty}
                            onChange={value => {
                                dispatch({type:'changeqty',payload:{qty:value,_id:item._id}})
                            }}
                        />
                    </List.Item>
                    </SwipeAction>
                ))
            }
        </List>
        <div className='actions'>
            <Checkbox defaultChecked>全选</Checkbox>
            <span className='price'>合计：<span>{totalPrice.toFixed(2)}</span></span>
            <Button color='danger'>去结算</Button>
        </div>
    </div>
}

Cart = withLogin(Cart)

export default Cart;